<?php
namespace app\datastruct\controller;
//单链表
class SingleLinkList
{
    public $header = null;
    public function __construct()
    {
       $this->header = new Node();
    }

    /**
     * 单链表头插一个元素
     * @param $data
     */
    public function addfirst($data)
    {
        $current = $this->header;//获取整个单链表
        $node = new Node($data);//待插入节点
        $node->next = $current;//将待插入节点的next指针指向头结点
        $this->header = $node;//更新整个链表
    }

    /**
     * 尾插
     * @param $data
     * @return $this
     */
    public function addlast($data)
    {

        $current = $this->header;
         while (!is_null($current->next)){
             $current = $current->next;
         }
         $node = new Node($data);
         $current->next = $node;
        return $this;
    }

    /**
     * 统计单链表节点个数
     * @return int
     */
    public function count()
    {
        $current = $this->header;
        $i = 0;
        while (!is_null($current->next)) {
            $i++;
            $current = $current->next;
        }
        return $i;
    }

    /**
     * 修改单链表中某个节点的值
     * @param $no
     * @param $data
     * @return $this|bool
     */
    public function update($no,$data)
    {
        if($no > $this->count()){
            return false;
        }
        $current = $this->header;
        for($i = 0;$i<$no;$i++){
            $current = $current->next;
        }
        $current->data = $data;
        return $this;
    }

    /**
     * 删除单链表中指定的一个元素
     * @param $no
     * @return bool
     */
    public function del($no)
    {
        if ($no > $this->count()){
            return false;
        }
        $current = $this->header;
        for ($i = 0; $i < $no - 1; $i++) {
            $current = $current->next;
        }
        $current->next = $current->next->next;
        return true;
    }

    /**
     * 单链表中在指定节点后插入新节点
     * @param $no
     * @param $data
     * @return bool
     */
    public function insert($no,$data)
    {
        if ($no > $this->count()){
            return false;
        }
        $current = $this->header;
        $node = new Node($data);
        for ($i=0;$i<$no;$i++){
            $current = $current->next;
        }
        $node->next = $current->next;
        $current->next = $node;
        return true;
    }

    /**
     * 遍历单链表中所有节点的数据值
     */
    public function show()
    {
        $current = $this->header;
        while (!is_null($current->next)){
            $current = $current->next;
            echo $current->data.'<br/>';
        }
    }
}
